package subject_set.top101;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;

/**
 * @author haomin
 * @date 2022/11/01 20:22
 **/
public class BM26 {
    public class Solution {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
            if(root == null) return res;
            Deque<TreeNode> q = new LinkedList<>();
            q.offer(root);
            while(!q.isEmpty()){
                int size = q.size();
                ArrayList<Integer> ret = new ArrayList<>();
                for(int i = 0; i < size; ++i){
                    TreeNode cur = q.poll();
                    ret.add(cur.val);
                    if(cur.left != null) q.offer(cur.left);
                    if(cur.right != null) q.offer(cur.right);
                }
                res.add(new ArrayList<>(ret));
            }
            return res;
        }
    }

    public class Solution2 {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
            preOrder(root, 0);
            return res;
        }
        private void preOrder(TreeNode cur, int k){
            if(cur == null) return;
            if(res.size() <= k) res.add(new ArrayList<>());
            res.get(k).add(cur.val);
            preOrder(cur.left, k+1);
            preOrder(cur.right, k+1);
        }
    }
}